package com.example.alarm.mvvm.activity

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.alarm.R
import com.example.alarm.mvvm.adapter.RvDownloadAdapter
import com.example.alarm.mvvm.adapter.RvShowWordAdapter
import com.example.alarm.mvvm.bean.ReqAttachmentBean
import com.example.alarm.mvvm.widget.DealStatusSelectDialog
import com.example.login.mvvm.viewmodel.AlarmViewModel
import com.gsafety.libraryktx.base.BaseActivity
import com.gsafety.libraryktx.bean.WarnData
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.config.Constant.Companion.CODE_CB
import com.gsafety.libraryktx.config.Constant.Companion.CODE_COMPLETE
import com.gsafety.libraryktx.config.Constant.Companion.CODE_FEEDBACK
import com.gsafety.libraryktx.config.Constant.Companion.CODE_JJ
import com.gsafety.libraryktx.config.Constant.Companion.CODE_PS
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_CUIBAN
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_FEEDBACK
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_FINISH
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_NO_RESOLVE
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_PISHI
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_RECEIVE
import com.gsafety.libraryktx.config.Constant.Companion.DEAL_STATE_RESOLVE
import com.gsafety.libraryktx.core.RouterConstants
import com.gsafety.libraryktx.expand.create
import com.gsafety.libraryktx.expand.toast
import com.gsafety.libraryktx.manager.UserManager
import com.gsafety.libraryktx.util.AppUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.alarm_bottom_feedback.*
import kotlinx.android.synthetic.main.alarm_detail_activity_layout.*
import java.util.*

@Route(path = RouterConstants.ALARM_DETAIL_ACTIVITY)
class AlarmDetailActivity:BaseActivity(), DealStatusSelectDialog.OnReceiveAlarmClickListener {
    var mDealDialog:DealStatusSelectDialog?=null
    var recordsBean : WarnData.RecordsBean? = null
    var mVsFeedback: View? = null
    private lateinit var mv: AlarmViewModel
    var userName = ""
    var procUnit = ""
    var attachments: ReqAttachmentBean = ReqAttachmentBean()
    var dealType = ""
    var iv_save:ImageView?= null
    var tv_save:TextView?= null

    companion object {
        fun startIntent(ctx: Context, intent: Intent) {
            intent.setClass(ctx, AlarmDetailActivity::class.java)
            ctx.startActivity(intent)
        }
    }

    override fun initView() {
        mv = AlarmViewModel()
        mv = create(AlarmViewModel::class)
        if(mDealDialog == null){
            mDealDialog = DealStatusSelectDialog(this)
            mDealDialog?.mOnReceiveAlarmClickListener = this
        }
        findViewById<TextView>(R.id.title_name).text = "监测预警详情"
    }

    private fun initListeners(){
        var tv_receive_alarm = vs_feedback_deal.findViewById<View>(R.id.tv_receive_alarm)
        tv_receive_alarm?.setOnClickListener{
//            cl_bottom_content_parent.visibility = View.VISIBLE
            dealType = DEAL_STATE_RECEIVE
//            tv_bottom_title.text = "接警信息"
            mDealDialog?.dealType = DEAL_STATE_RECEIVE
            mDealDialog?.show()
        }

        var tv_pishi_btn = vs_feedback_deal.findViewById<View>(R.id.tv_pishi_btn)
        tv_pishi_btn?.setOnClickListener{
            cl_bottom_content_parent.visibility = View.VISIBLE
            dealType = DEAL_STATE_PISHI
            tv_bottom_title.text = "批示信息"
        }

        var tv_cuiban_btn = vs_feedback_deal.findViewById<View>(R.id.tv_cuiban_btn)
        tv_cuiban_btn?.setOnClickListener{
            cl_bottom_content_parent.visibility = View.VISIBLE
            dealType = DEAL_STATE_CUIBAN
            tv_bottom_title.text = "催办信息"
        }

        bt_send?.setOnClickListener{
            if(et_bottom_info.text.toString().isNullOrEmpty()){
                toast("请输入内容")
                return@setOnClickListener
            }
            mv.addDisposalProc(
                recordsBean?.pid!!,
                "",
                dealType,
                recordsBean?.adtevtStatus.toString(),
                et_bottom_info.text.toString(),
                procUnit,
                userName,
                "",
                AppUtil.getYmdHmssSSS(
                    Date()
                ),
                attachments
            )
        }


        var tv_feedback_btn = vs_feedback_deal.findViewById<View>(R.id.tv_feedback_btn)
        tv_feedback_btn?.setOnClickListener{
            var intent = Intent(this, FeedbackActivity().javaClass)
            intent.putExtra("type", DEAL_STATE_FEEDBACK)
            intent.putExtra("records", recordsBean)
            startActivityForResult(intent, Constant.DEAL_REQ_FEEDBACK_CODE)
        }

        var tv_deal_finish = vs_feedback_deal.findViewById<View>(R.id.tv_deal_finish)
        tv_deal_finish?.setOnClickListener{
//            var intent = Intent(this, FeedbackActivity().javaClass)
//            intent.putExtra("type", DEAL_STATE_FINISH)
//            intent.putExtra("records", recordsBean)
//            startActivityForResult(intent, Constant.DEAL_REQ_FINISH_CODE)
            dealType = DEAL_STATE_RESOLVE
            mDealDialog?.dealType = dealType
            mDealDialog?.show()
        }

        fl_top_content?.setOnClickListener {
            cl_bottom_content_parent.visibility = View.GONE
            hideInput()
        }

        var cl_attend_parent = vs_feedback_deal.findViewById<View>(R.id.cl_attend_parent)
        cl_attend_parent?.setOnClickListener {
            if(recordsBean?.attended!!){
                mv.cancelAttention(recordsBean?.pid!!)
            }else{
                mv.setAttention(recordsBean?.pid!!)
            }
        }
    }

    override fun initData() {
        userName = UserManager.getInstance().getUser()?.userName + ""
        procUnit = UserManager.getInstance().getUser()?.orgName + ""
        recordsBean = intent.getSerializableExtra("records") as WarnData.RecordsBean?

        dealData()
        reqDealList()
    }

    private fun updateView(){
        var hasJieJin:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_JJ)!!
        var hasCuiBan:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_CB)!!
        var hasPiShi:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_PS)!!
        var hasFeedback:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_FEEDBACK)!!
        var hasFinish:Boolean = UserManager.getInstance().appModelCodes()?.contains(CODE_COMPLETE)!!
        vs_feedback_deal.let {
            it.removeAllViews()
        }

        recordsBean?.let {
            when(it.adtevtStatus){
                Constant.NO_DEAL_CODE.toInt() -> { // 待处置
//                    hasCuiBan = (Date().time - AppUtil.getTimeMil(it.pubTime)) / 3600f / 1000f > 12
                    if (hasJieJin && !hasPiShi && !hasCuiBan) { // 只显示接警
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_receive,vs_feedback_deal,false))
                    }
                    if (!hasJieJin && !hasPiShi && !hasCuiBan) {
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_save,vs_feedback_deal,false))
                    }
                    if (hasPiShi || hasCuiBan) {
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_feedback,vs_feedback_deal,false))
                    }
                    var tv_receive_alarm = vs_feedback_deal.findViewById<View>(R.id.tv_receive_alarm)
                    var tv_pishi_btn = vs_feedback_deal.findViewById<View>(R.id.tv_pishi_btn)
                    var tv_cuiban_btn = vs_feedback_deal.findViewById<View>(R.id.tv_cuiban_btn)
                    tv_receive_alarm?.visibility = if (hasJieJin) View.VISIBLE else View.GONE
                    tv_pishi_btn?.visibility = View.GONE
                    tv_cuiban_btn?.visibility = if (hasCuiBan) View.VISIBLE else View.GONE
                }
                Constant.IN_DEAL_CODE.toInt() -> { // 处置中
                    if (!hasPiShi && !hasCuiBan && !hasFeedback) {
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_save,vs_feedback_deal,false))
                    } else {
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_feedback,vs_feedback_deal,false))
                    }
                    var tv_feedback_btn = vs_feedback_deal.findViewById<View>(R.id.tv_feedback_btn)
                    var tv_pishi_btn = vs_feedback_deal.findViewById<View>(R.id.tv_pishi_btn)
                    var tv_deal_finish = vs_feedback_deal.findViewById<View>(R.id.tv_deal_finish)
                    tv_pishi_btn?.visibility = if (hasPiShi) View.VISIBLE else View.GONE
                    tv_feedback_btn?.visibility = if (hasFeedback) View.VISIBLE else View.GONE
                    tv_deal_finish?.visibility = if (hasFinish) View.VISIBLE else View.GONE
                }
                Constant.HAS_DEAL_CODE.toInt() -> { // 已解除
                    if (hasPiShi) {
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_feedback,vs_feedback_deal,false))
                    }else{
                        vs_feedback_deal.addView(LayoutInflater.from(this).inflate(R.layout.alarm_bottom_save,vs_feedback_deal,false))
                    }
                    var tv_pishi_btn = vs_feedback_deal.findViewById<View>(R.id.tv_pishi_btn)
                    tv_pishi_btn?.visibility = if (hasPiShi) View.VISIBLE else View.GONE
                }
            }
        }
        tv_baseInfo_title1_right.text = recordsBean?.adtevtName
        when(recordsBean?.adtevtLevel){
            1 -> {
                tv_baseInfo_title2_right.setTextColor(resources.getColor(R.color.common_color_first_level))
                tv_baseInfo_title2_right.text = "一级报警"
            }
            2 -> {
                tv_baseInfo_title2_right.setTextColor(resources.getColor(R.color.common_color_second_level))
                tv_baseInfo_title2_right.text = "二级报警"
            }
            3 -> {
                tv_baseInfo_title2_right.setTextColor(resources.getColor(R.color.common_color_third_level))
                tv_baseInfo_title2_right.text = "三级报警"
            }
            4 -> {
                tv_baseInfo_title2_right.setTextColor(resources.getColor(R.color.common_color_fourth_level))
                tv_baseInfo_title2_right.text = "四级报警"
            }
        }
        when (recordsBean?.adtevtStatus) {
            Constant.NO_DEAL_CODE.toInt() -> iv_alarm_state.setImageResource(R.mipmap.common_tag_no_deal)
            Constant.IN_DEAL_CODE.toInt() -> iv_alarm_state.setImageResource(R.mipmap.common_tag_in_deal)
            Constant.HAS_DEAL_CODE.toInt() -> iv_alarm_state.setImageResource(R.mipmap.common_tag_has_finish)
        }
        tv_baseInfo_title3_right.text = recordsBean?.pubTime
        tv_baseInfo_title4_right.text = recordsBean?.adtevtGeoaddr
        tv_baseInfo_title5_right.text = recordsBean?.relAlarmNote
        recordsBean?.fzjcdesc.let {
            if(!it.isNullOrEmpty()) {
                tv_assistant_decision_mark_right.text = it
                gp_assistant_decision.visibility = View.VISIBLE
            }
        }
        iv_save = vs_feedback_deal.findViewById<ImageView>(R.id.iv_save)
        tv_save = vs_feedback_deal.findViewById<TextView>(R.id.tv_save)
        when (recordsBean?.attended) {
            true -> {
                iv_save?.setImageResource(R.mipmap.common_icon_has_saved1)
                tv_save?.text = "取消"
            }
            false -> {
                iv_save?.setImageResource(R.mipmap.common_icon_save1)
                tv_save?.text = "关注"
            }
        }
        initListeners()
    }

    /**
     * 隐藏键盘
     */
    protected fun hideInput() {
        val imm: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        val v = window.peekDecorView()
        if (null != v) {
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }

    private fun reqDealList() {
        if(recordsBean?.pid == null){
            return
        }
        mv.currWarningDetail(recordsBean?.pid!!)
    }

    fun dealData(){
        mv.addDisposalProcValue.observe(this, androidx.lifecycle.Observer {
            if (!mv.addDisposalProcValue.value.isNullOrEmpty()) {
                cl_bottom_content_parent.visibility = View.GONE
                when(dealType){
                    DEAL_STATE_RECEIVE->{
                        recordsBean?.adtevtStatus = Constant.IN_DEAL_CODE.toInt()
                        reqDealList()
                    }
                    DEAL_STATE_PISHI->{
                        reqDealList()
                    }
                    DEAL_STATE_CUIBAN->{
                        reqDealList()
                    }
                    DEAL_STATE_RESOLVE->{
                        recordsBean?.adtevtStatus = Constant.HAS_DEAL_CODE.toInt()
                        reqDealList()
                    }
                    DEAL_STATE_NO_RESOLVE->{
                        reqDealList()
                    }
                }
                Toast.makeText(this, mv.addDisposalProcValue.value, Toast.LENGTH_SHORT).show()
            }
        })
        mv.setAttendValue.observe(this, androidx.lifecycle.Observer {
            if (mv.setAttendValue.value == true) {
                recordsBean?.attended = true
                iv_save?.setImageResource(R.mipmap.common_icon_has_saved1)
                tv_save?.text = "取消"
                Toast.makeText(this, "关注成功！", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "关注失败！", Toast.LENGTH_SHORT).show()
            }
        })

        mv.cancelAttendValue.observe(this, androidx.lifecycle.Observer {
            if (mv.cancelAttendValue.value == true) {
                recordsBean?.attended = false
                iv_save?.setImageResource(R.mipmap.common_icon_save1)
                tv_save?.text = "关注"
                Toast.makeText(this, "取消关注成功！", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "取消关注失败！", Toast.LENGTH_SHORT).show()
            }
        })

        mv.currWarningDetailValue.observe(this, androidx.lifecycle.Observer {
            updateView()
            if(!it.judanaDesc.isNullOrEmpty()){
                tv_judge_title_right.text = it.judanaDesc
                gp_judge.visibility = View.VISIBLE
            }
            if(!it.docs.isNullOrEmpty()){
                gp_scene.visibility = View.VISIBLE
            }
            gv_analyse_pic.layoutManager = LinearLayoutManager(this)
            gv_analyse_pic.adapter = RvShowWordAdapter(it.docs)

            if (!it.processes.isNullOrEmpty()) {
                ll_feedback_parent.removeAllViews()
                it.processes.forEachIndexed { index, it ->
                    var view = LayoutInflater.from(this)
                        .inflate(R.layout.alarm_feedback_info_item, ll_feedback_parent, false)
                    var tv_deal_person = view.findViewById<TextView>(R.id.tv_deal_person)
                    var tv_person_work = view.findViewById<TextView>(R.id.tv_person_work)
                    var tv_time = view.findViewById<TextView>(R.id.tv_time)
                    var tv_deal_type = view.findViewById<TextView>(R.id.tv_deal_type)
                    var tv_alarm_reason = view.findViewById<TextView>(R.id.tv_alarm_reason)
                    var v_content_divider = view.findViewById<View>(R.id.v_content_divider)
                    var iv_deal_icon = view.findViewById<ImageView>(R.id.iv_deal_icon)
                    var gv_pic_list = view.findViewById<RecyclerView>(R.id.gv_pic_list)
                    var rvDownloadAdapter = RvDownloadAdapter(it.docs)
                    gv_pic_list.adapter = rvDownloadAdapter
                    gv_pic_list.layoutManager = GridLayoutManager(this,4)
                    rvDownloadAdapter.setViewModel(mv,this@AlarmDetailActivity)
                    rvDownloadAdapter.setOnItemClickListener { adapter, view, position ->
                        PreviewImageActivity.startIntent(this,it.docs,position)
                    }
                    var dealType = ""
                    when (it.contFlag.toString()) {
                        DEAL_STATE_CUIBAN -> {
                            dealType = "已催办"
                            iv_deal_icon.setImageResource(if (index == 0) R.mipmap.icon_cuiban2 else R.mipmap.icon_cuiban1)
                        }
                        DEAL_STATE_RECEIVE -> {
                            dealType = "已接警"
                            iv_deal_icon.setImageResource(if (index == 0) R.mipmap.icon_rev_alarm_pro2 else R.mipmap.icon_rev_alarm_pro1)
                        }
                        DEAL_STATE_FEEDBACK -> {
                            dealType = "已反馈"
                            iv_deal_icon.setImageResource(if (index == 0) R.mipmap.icon_feedback_pro2 else R.mipmap.icon_feedback_pro1)
                        }
                        DEAL_STATE_PISHI -> {
                            dealType = "已批示"
                            iv_deal_icon.setImageResource(if (index == 0) R.mipmap.icon_instr_pro2 else R.mipmap.icon_instr_pro1)
                        }
                        DEAL_STATE_FINISH -> {
                            dealType = "已完成处置"
//                            tv_alarm_reason.visibility = View.VISIBLE
//                            v_content_divider.visibility = View.VISIBLE
                            tv_alarm_reason.text = it.adtevtOccureason
                            iv_deal_icon.setImageResource(R.mipmap.icon_has_finish)
                        }
                        DEAL_STATE_RESOLVE -> {
                            dealType = "已解除"
                            iv_deal_icon.setImageResource(R.mipmap.icon_has_finish)
                        }
                        DEAL_STATE_NO_RESOLVE -> {
                            dealType = "未解除"
                            iv_deal_icon.setImageResource(R.mipmap.icon_has_finish)
                        }
                    }
                    tv_deal_person.text = "【" + it.procUnit + "】 " + it.procerInfo
                    tv_person_work.text = it.dispNote
                    tv_time.text = it.dispTime
                    tv_deal_type.text = dealType
                    ll_feedback_parent.addView(view)
                }
            }
            var view = LayoutInflater.from(this)
                .inflate(R.layout.alarm_first_info_item, ll_feedback_parent, false)
            var iv_deal_icon = view.findViewById<ImageView>(R.id.iv_deal_icon)
            var tv_alarm_info_title = view.findViewById<TextView>(R.id.tv_alarm_info_title)
            var tv_alarm_info_level = view.findViewById<TextView>(R.id.tv_alarm_info_level)
            var tv_alarm_info_time = view.findViewById<TextView>(R.id.tv_alarm_info_time)
            iv_deal_icon.setImageResource(R.mipmap.icon_alarm_pro0)
            tv_alarm_info_title.text = recordsBean?.adtevtName
            tv_alarm_info_time.text = recordsBean?.pubTime
            when (recordsBean?.adtevtLevel) {
                1 -> {
                    tv_alarm_info_level.setTextColor(resources.getColor(R.color.common_color_first_level))
                    tv_alarm_info_level.text = "一级报警"
                }
                2 -> {
                    tv_alarm_info_level.setTextColor(resources.getColor(R.color.common_color_second_level))
                    tv_alarm_info_level.text = "二级报警"
                }
                3 -> {
                    tv_alarm_info_level.setTextColor(resources.getColor(R.color.common_color_third_level))
                    tv_alarm_info_level.text = "三级报警"
                }
                4 -> {
                    tv_alarm_info_level.setTextColor(resources.getColor(R.color.common_color_fourth_level))
                    tv_alarm_info_level.text = "四级报警"
                }
            }
            if (it.processes.isNullOrEmpty()) {
                view.findViewById<View>(R.id.v_vertical_divider).visibility = View.GONE
            }
            ll_feedback_parent.addView(view)
        })
    }

    override fun getLayoutId(): Int {
        return R.layout.alarm_detail_activity_layout
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == Constant.DEAL_REQ_FEEDBACK_CODE&&resultCode == Constant.DEAL_RES_OK_CODE){
            reqDealList()
        }else if(requestCode == Constant.DEAL_REQ_FINISH_CODE&&resultCode == Constant.DEAL_RES_OK_CODE){
            recordsBean?.adtevtStatus = Constant.HAS_DEAL_CODE.toInt()
            reqDealList()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(recordsBean?.adtevtStatus == Constant.IN_DEAL_CODE.toInt()){
            LiveEventBus.get(Constant.EventBus_KEY_Alarm_Deal_Switch,String::class.java).post(Constant.IN_DEAL_CODE)
        }else if(recordsBean?.adtevtStatus == Constant.HAS_DEAL_CODE.toInt()){
            LiveEventBus.get(Constant.EventBus_KEY_Alarm_Deal_Switch,String::class.java).post(Constant.HAS_DEAL_CODE)
        }
//        setResult(resultCode)
    }

    override fun receiveAlarmClick(msg:String) {
        if(msg == resources.getString(R.string.alarm_sure_no_pass)){
            dealType = DEAL_STATE_NO_RESOLVE
        }
        mv.addDisposalProc(
            recordsBean?.pid!!,
            "",
            dealType,
            recordsBean?.adtevtStatus.toString(),
            msg,
            procUnit,
            userName,
            "",
            AppUtil.getYmdHmssSSS(
                Date()
            ),
            attachments
        )
    }

}